package com.rsa.decrypt;

import com.rsa.common.RasCommon;
import com.rsa.tools.RsaTools;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.PrivateKey;

/**
 * @author lf
 * @Description: 数据解密
 * @date 2020/7/30 12:36
 */
public class DecryptTools {

    private static final Logger log = LoggerFactory.getLogger(DecryptTools.class);
    /**
     * 数据解密
     * @param data  带解密数据
     * @param privateKey    本服务私钥
     * @return  明文
     * @throws Exception
     */
    public static String dataDecrypt(String data, String privateKey) throws Exception {
        log.info("对外提供的解密方法...");
        return decrypt(data, RsaTools.getPrivateKey(privateKey));
    }

    /**
     * RSA解密
     * @param data 待解密数据
     * @param privateKey 私钥
     * @return 明文
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > RasCommon.MAX_DECRYPT_BLOCK[0]) {
                cache = cipher.doFinal(dataBytes, offset, RasCommon.MAX_DECRYPT_BLOCK[0]);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * RasCommon.MAX_DECRYPT_BLOCK[0];
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }
}
